package controller

import (
	"elegantGo/chapter17/controller/response"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"net/http"
)

var validationErrors validator.ValidationErrors

type HandlerFunc func(c *gin.Context) (response.Data, error)

type Handler struct {
}

func (handler *Handler) Wrapper(handlerFunc HandlerFunc) func(c *gin.Context) {
	return func(c *gin.Context) {
		//defer func() {
		//	if r := recover(); r != nil {
		//		msg := fmt.Sprintf("%s： %v", response.Msg[response.UnknownError], r)
		//		c.JSON(http.StatusOK, response.Response{Code: response.UnknownError, Message: msg})
		//	}
		//}()

		data, err := handlerFunc(c)
		if err == nil {
			c.JSON(http.StatusOK, response.Response{Code: response.OK, Message: response.Msg[response.OK], Data: data, Success: true})
			return
		}

		code := response.BusinessError
		message := err.Error()

		if errors.Is(err, validationErrors) {
			code = response.InvalidArgument
		} else {
			var respError response.Error
			if errors.As(err, &respError) {
				code = respError.Code
			}
		}

		c.JSON(http.StatusOK, response.Response{Code: code, Message: message, Data: data})
	}
}
